package com.ruibang.glass.produce.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.Constants;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceCreate;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceStatus;
import com.ruibang.glass.common.domain.camunda.BpmTaskApproveReq;
import com.ruibang.glass.common.domain.file.FileInfo;
import com.ruibang.glass.produce.domain.req.AnalysisReportReq;
import com.ruibang.glass.produce.entity.AnalysisReport;
import com.ruibang.glass.produce.feign.CamundaApi;
import com.ruibang.glass.produce.feign.FileApi;
import com.ruibang.glass.produce.mapper.AnalysisReportMapper;
import com.ruibang.glass.produce.service.AnalysisReportService;
//import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.model.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 质量-理化-理化分析报告 服务实现类
 * </p>
 *
 * @author songJinKang
 * @since 2024-03-22
 */
@Slf4j
@Service
public class AnalysisReportServiceImpl extends ServiceImpl<AnalysisReportMapper, AnalysisReport> implements AnalysisReportService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private FileApi fileApi;

    @Autowired
    private CamundaApi camundaApi;

//    @Autowired
//    private RedisSingleService redisService;

    @Autowired
    private RedisSingleService redisService;

    @Override
    public IPage<AnalysisReport> pageQuery(AnalysisReportReq analysisReportReq) {
        QueryWrapper<AnalysisReport> qw = new QueryWrapper<>();
        qw.lambda().eq(AnalysisReport::getIsDelete, Constants.ZERO_STR);
        qw.lambda().like(StringUtils.isNotBlank(analysisReportReq.getReportName()), AnalysisReport::getReportName, analysisReportReq.getReportName());
        qw.lambda().eq(StringUtils.isNotBlank(analysisReportReq.getProcesses()), AnalysisReport::getProcesses, analysisReportReq.getProcesses());
        if (analysisReportReq.getStartDate() != null && analysisReportReq.getEndDate() != null) {
            qw.lambda().ge(AnalysisReport::getDate, analysisReportReq.getStartDate());
            qw.lambda().le(AnalysisReport::getDate, analysisReportReq.getEndDate());
        }
        qw.lambda().orderByDesc(AnalysisReport::getCreateTime);
        Page<AnalysisReport> page = this.page(new Page<>(analysisReportReq.getPageNo(), analysisReportReq.getPageSize()), qw.lambda());

        if (page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
            //文件信息
            List<AnalysisReport> analysisReports = page.getRecords();
            List<String> fileIds = analysisReports.stream().map(AnalysisReport::getFile).collect(Collectors.toList());
            ResultBody<List<FileInfo>> resultBody = fileApi.getFileInfoByBusinessIds(fileIds);
            if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
                List<FileInfo> fileInfos = resultBody.getData();
                Map<String, FileInfo> fileMap = fileInfos.stream().collect(Collectors.toMap(FileInfo::getBusinessId, e -> e, (oldEl, newEl) -> newEl));
                for (AnalysisReport analysisReport : analysisReports) {
                    analysisReport.setFileInfo(fileMap.get(analysisReport.getId()));
                }
            }
            //流程信息
            List<String> ids = analysisReports.stream().map(AnalysisReport::getId).collect(Collectors.toList());
            ResultBody<List<BpmProcessInstanceStatus>> bpmResultBody = camundaApi.queryProcessInstanceStatus(ids);
            if (bpmResultBody != null && CollectionUtils.isNotEmpty(bpmResultBody.getData())) {
                List<BpmProcessInstanceStatus> bpmProcessInstanceStatusList = bpmResultBody.getData();
                Map<String, BpmProcessInstanceStatus> bpmProcessInstanceStatusMap = bpmProcessInstanceStatusList.stream().collect(Collectors.toMap(BpmProcessInstanceStatus::getBusinessKey, e -> e, (oldEl, newEl) -> newEl));
                for (AnalysisReport analysisReport : analysisReports) {
                    BpmProcessInstanceStatus bpmProcessInstanceStatus = bpmProcessInstanceStatusMap.get(analysisReport.getId());
                    if (bpmProcessInstanceStatus != null) {
                        String userId = bpmProcessInstanceStatus.getUserId();
                        if (StringUtils.isNotBlank(userId)) {
                            Object userNameObj = redisService.hget(RedisKey.USER_GROUP_TYPE, userId);
                            analysisReport.setApproveUserId(userId);
                            if (userNameObj != null) {
                                analysisReport.setApproveUserName(userNameObj.toString());
                            }
                        }
                        analysisReport.setStatus(bpmProcessInstanceStatus.getResult());
                        analysisReport.setProcessInstanceId(bpmProcessInstanceStatus.getProcessInstanceId());
                        analysisReport.setNodeName(bpmProcessInstanceStatus.getNodeName());
                    }
                }
            }
        }


        return page;
    }

    @Override
    public void delete(String id) {
        lambdaUpdate().eq(AnalysisReport::getId, id).set(AnalysisReport::getIsDelete, Constants.ONE_STR).update();
    }

    @Override
    public void insert(AnalysisReport analysisReport) {
        //保存
        analysisReport.setIsDelete(Constants.ZERO_STR);
        setUserName(analysisReport);
        this.save(analysisReport);

        //发起流程
        BpmProcessInstanceCreate bpmProcessInstanceCreate = new BpmProcessInstanceCreate();
        Map<String, Object> variables = new HashMap<>();
        variables.put(Constants.PROCESS_INSTANCE_STARTER_USER_ID, analysisReport.getCreateUserId());
        variables.put(Constants.PROCESS_INSTANCE_BUSINESS_KEY, analysisReport.getId());
        variables.put(Constants.PROCESS_INSTANCE_MENU_ID, analysisReport.getMenuId());
        bpmProcessInstanceCreate.setVariables(variables);
        bpmProcessInstanceCreate.setBusinessKey(analysisReport.getId());
        bpmProcessInstanceCreate.setMenuId(analysisReport.getMenuId());
        String processId = commonService.startProcess(bpmProcessInstanceCreate);

        //直接通过第一流程节点
        if (StringUtils.isNotBlank(processId)) {
            BpmTaskApproveReq bpmTaskApproveReq = new BpmTaskApproveReq();
            bpmTaskApproveReq.setId(processId);
            bpmTaskApproveReq.setUserId(analysisReport.getCreateUserId());
            camundaApi.approve(bpmTaskApproveReq);
        }
    }

    @Override
    public void edit(AnalysisReport analysisReport) {
        setUserName(analysisReport);
        //更新
        this.updateById(analysisReport);
    }

    private void setUserName(AnalysisReport analysisReport) {
        String checkById = analysisReport.getCheckById();
        String createUserId = analysisReport.getCreateUserId();
        if (StringUtils.isNotBlank(checkById)) {
            Object userObj = redisService.hget(RedisKey.USER_GROUP_TYPE, checkById);
            if (userObj != null && org.apache.commons.lang3.StringUtils.isNotBlank(userObj.toString())) {
                analysisReport.setCheckBy(userObj.toString());
            }
        }else{
            analysisReport.setCheckBy("");
        }
        if (StringUtils.isNotBlank(createUserId)) {
            Object userObj = redisService.hget(RedisKey.USER_GROUP_TYPE, createUserId);
            if (userObj != null && org.apache.commons.lang3.StringUtils.isNotBlank(userObj.toString())) {
                analysisReport.setCreateUserName(userObj.toString());
            }
        }else{
            analysisReport.setCreateUserName("");
        }
    }

    @Override
    public AnalysisReport getDetails(String id) {
        AnalysisReport analysisReport = this.getById(id);
        //获取文件信息
        if (analysisReport != null) {
            ResultBody<FileInfo> result = fileApi.getDetails(analysisReport.getId());
            if (result != null && result.getData() != null) {
                analysisReport.setFileInfo(result.getData());
            }
        }
        return analysisReport;
    }
}
